//
//  NewsHomeViewController.m
//  555彩票
//
//  Created by zhoubo on 2017/7/4.
//  Copyright © 2017年 zhoubo. All rights reserved.
//

#import "NewsHomeViewController.h"
#import "Channel.h"
#import "Head.h"
#import "NewsTableViewController.h"
#import "NewsHomeViewCell.h"
#import "ChannelLabel.h"
#import "BmobSDK/Bmob.h"
#import "News.h"
#import "ZBPullDownRefreshView.h"

#import "SVProgressHUD.h"

@interface NewsHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIScrollView *channelView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;

@property (nonatomic,strong) NSArray* channels;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowlayout;

@property (nonatomic,strong) NSMutableDictionary* controllerCache;

@property (nonatomic,assign) int  currentIndex;

@property (nonatomic,assign) BOOL  isScorlling;

@property (nonatomic,assign) CGFloat  beginDragX;

@property (nonatomic,strong) NSArray* news;



@end

@implementation NewsHomeViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"home view will appear");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor ];
//    self.channelView.backgroundColor = [UIColor redColor];
    
    [self setChannelTitle];
    self.currentIndex = 0;
    ChannelLabel* label = self.channelView.subviews[self.currentIndex];
    label.scale = 1;  // 1 表示最大
    
    self.channelView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    NSLog(@"Home view did load");
    
    
}




-(void)setChannelTitle
{
    self.automaticallyAdjustsScrollViewInsets = NO;

    
    CGFloat margin = 15;
    CGFloat channelX = margin;
    for (NSString * name in self.channels) {
        ChannelLabel* label = [ChannelLabel labelWithTitle:name];
        
        __weak typeof (self) weakvc = self;
        __weak typeof(ChannelLabel*) weakLabel = label;
        
        [label setSelectedlabel:^{
            
            ChannelLabel* currentlabel = self.channelView.subviews[self.currentIndex];
            currentlabel.scale = 0;
            weakLabel.scale = 1;
            self.currentIndex = [weakvc.channelView.subviews indexOfObject:weakLabel];
            
            [weakvc.collectionview scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            
            CGFloat centerX = weakLabel.center.x;
            CGFloat halfW = SWidth * 0.5;

            CGFloat minuswidth = weakvc.channelView.contentSize.width - SWidth;
            CGFloat offset = centerX - halfW;
            if (offset<0) {
                
                offset = 0;
                

            }
            else if (offset > minuswidth)
            {
                offset = minuswidth;
            }
                
                
            [weakvc.channelView setContentOffset:CGPointMake(offset, 0) animated:YES];
            
        }];

        // 修改height 使之与scrollview的height相同
        label.frame = CGRectMake(channelX, 0, label.frame.size.width, 44);

        [self.channelView addSubview:label];
        
        channelX += label.frame.size.width + margin;
    }
    
    self.channelView.contentSize = CGSizeMake(channelX, 0);
    self.channelView.showsHorizontalScrollIndicator = false;
    

}



-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    // 设置item的尺寸
    self.flowlayout.itemSize = self.collectionview.bounds.size;
//    NSLog(@"%@",NSStringFromCGSize(self.collectionview.bounds.size));
    // 设置item之间的间隙
    self.flowlayout.minimumInteritemSpacing = 0;
    self.flowlayout.minimumLineSpacing = 0;
    
    // 设置方向
    self.flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 设置分页效果
    self.collectionview.pagingEnabled = YES;
    // 设置隐藏水平滚动条
    self.collectionview.showsHorizontalScrollIndicator = NO;
    // 禁止弹簧效果
    self.collectionview.bounces = NO;
    


    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.beginDragX = scrollView.contentOffset.x;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    ChannelLabel* leftlbl = nil;
    ChannelLabel* rightlbl = nil;
    
    
    CGFloat offset = scrollView.contentOffset.x / SWidth;
    
    int multi = 0;
    
    while (offset >= 1)
    {
        offset -= 1;
        multi += 1;
    }
    CGFloat nextscale =offset;
    
//    NSLog(@"滑动了%d倍屏,小数部分:%f",multi,offset);
    


        leftlbl = self.channelView.subviews[multi];
        rightlbl = self.channelView.subviews[multi+1];


    CGFloat centerX = 0;
    

    CGFloat currentscale = 1-nextscale;
    
    if (scrollView.contentOffset.x > self.beginDragX) {

        if (multi == self.channels.count-1) {
            rightlbl = nil;
        }
        
        //屏幕向右滚动(手指左滑)
        rightlbl.scale = nextscale;
        leftlbl.scale = currentscale;
        
        centerX = rightlbl.center.x;
        
        
    }
    else
    {

        // 左滑的时候要处理好最后滑到末尾时候的情况 否则会崩溃
        if (multi == self.channels.count-1) {
            leftlbl = self.channelView.subviews[multi-1];
            rightlbl = self.channelView.subviews[multi];
        }
        rightlbl.scale = nextscale;
        leftlbl.scale = currentscale;
        
        
        centerX = leftlbl.center.x;
        
        
    }
    
    
    

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    CGFloat index = scrollView.contentOffset.x / SWidth;
    self.currentIndex = index;
    ChannelLabel* label = self.channelView.subviews[(int)index];
    CGFloat centerX = label.center.x;

    
    CGFloat halfW = SWidth * 0.5;
    
    CGFloat minuswidth = self.channelView.contentSize.width - SWidth;
    CGFloat offsetX = centerX - halfW;
    if (offsetX<0) {
        
        offsetX = 0;
        
        
    }
    else if (offsetX > minuswidth)
    {
        offsetX = minuswidth;
    }
    
    
    [self.channelView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    

}


-(void)beforePlanning:(UIScrollView*)scrollView
{
    ChannelLabel* currentLabel = self.channelView.subviews[self.currentIndex];
    ChannelLabel* nextLabel = nil;
    
    // 活的当前可看见的cell对应的item (可能是两个)
    NSArray* indexpaths = [self.collectionview indexPathsForVisibleItems];
    for (NSIndexPath* indexpath in indexpaths) {
        if (indexpath.item != self.currentIndex) {
            nextLabel = self.channelView.subviews[indexpath.row];
            break;
        }
        
    }
    // 保证无论滚动到哪里  缩放系数始终是在0-1范围内.取绝对值
    CGFloat nextscale = ABS(scrollView.contentOffset.x / scrollView.bounds.size.width - self.currentIndex);
    CGFloat currentScale = 1 - nextscale;
    
    currentLabel.scale = currentScale;
    nextLabel.scale  = nextscale;
    
    self.isScorlling = YES;

    
    CGFloat centerX = nextLabel.center.x;
    CGFloat halfW = SWidth * 0.5;
    
    CGFloat minuswidth = self.channelView.contentSize.width - SWidth;
    CGFloat offset = centerX - halfW;
    if (offset<0) {
        
        offset = 0;
        
        
    }
    else if (offset > minuswidth)
    {
        offset = minuswidth;
    }
    
    
    [self.channelView setContentOffset:CGPointMake(offset, 0) animated:YES];

}








/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.channels.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     NewsHomeViewCell* cell =    [collectionView dequeueReusableCellWithReuseIdentifier:@"channelCell" forIndexPath:indexPath];
    
    // 将上一个控制器的view移除
    [cell.newsController.view removeFromSuperview];
    NewsTableViewController* con = [self newsVC:self.channels[indexPath.row]];
    
    con.index = indexPath.row;
    cell.newsController = con;
    
    if (indexPath.row == 0) {
        [cell.newsController viewWillAppear:YES];
    }
    

    
    // 重要：如果控制器的view互为父子关系，则控制器之间必须也互为父子关系
    if(![self.childViewControllers containsObject:cell.newsController]) {
        [self addChildViewController:cell.newsController];
    }
    
    return cell;
}


-(NewsTableViewController*)newsVC:(NSString*)key
{
    NewsTableViewController* con = self.controllerCache[key];
    
    if (con == nil) {
        UIStoryboard * sb = [UIStoryboard storyboardWithName:@"NewsTableViewController" bundle:nil];
        con = sb.instantiateInitialViewController;
        
        con.removeCacheBlock = ^{
          
            [self.controllerCache removeObjectForKey:key];
            
        };
        

        
        //添加缓存
        [self.controllerCache setObject:con forKey:key];
        
        

    }
    
    return con;
}



-(NSArray *)channels
{
    if (_channels == nil) {
        _channels = [Channel channels];
    }
    return _channels;
}

-(NSMutableDictionary *)controllerCache
{
    if (_controllerCache == nil) {
        _controllerCache = [[NSMutableDictionary alloc]init];
        
    }
    return _controllerCache;
}


@end
